<!-- 上单表 -->
<template>
    <div >
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="`${statisticalDate}-${storehouse}-上单表`"
            @back="() => $router.go(-1)"
        >
            <div class='table-page-search-wrapper'>
                <a-form layout='inline'>
                    <a-row :gutter='48'>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="商品信息">
                                <a-select v-model="goodsCateId" placeholder="请选择" allowClear @change="selGoods">
                                    <a-select-option v-for="(item,i) in goodsList" :key="i" :value="item.id+','+item.cateId">{{item.name}}-{{item.cateName}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="颜色">
                                <a-select v-model="colorId" placeholder="请选择" allowClear @change="getData">
                                    <a-select-option v-for="(item,i) in colorsList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="等级">
                                <a-select v-model="grade" placeholder="请选择" allowClear @change="getData">
                                    <a-select-option v-for="(item,i) in gradeList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="规格">
                                <a-select v-model="specId" placeholder="请选择" allowClear @change="getData">
                                    <a-select-option v-for="(item,i) in specList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <!-- <a-col :md='16' :sm='24'>
                            <a-range-picker @change="onChange" :show-time="{ format: 'HH:mm:ss' }" />
                        </a-col> -->
                        <a-col :md='8' :sm='24'>
                        </a-col>
                        <a-col :md='8' :sm='24'>
                            <a-form-item >
                                <a-button type='primary' style="margin-right: 20px" @click="getData">查询</a-button>
                                <a-button type="" icon="upload" @click="downloadData()">导出数据</a-button>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>  

            <a-table size="small" :columns="columns" :data-source="dataList" :loading="isload" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" border>
                <div slot="grade" slot-scope="grade" > 
                    <div v-for="(item,i) in gradeList" :key="i">
                        <a-tag v-if="item.name == grade" :color="colors[i%13]">{{item.name}} </a-tag>
                    </div>
                </div>
                <div slot="specId" slot-scope="specId">
                    <div v-for="(item,i) in specList" :key="i">
                        <a-tag v-if="item.id == specId" :color="colors[i%13]">{{item.name}} </a-tag>
                    </div>
                </div>
                <div slot="colorId" slot-scope="colorId">
                    <div v-for="(item,i) in colorsList" :key="i">
                        <a-tag v-if="item.id == colorId" :color="colors[i%13]">{{item.name}} </a-tag>
                    </div>
                </div>
                <div slot="lastTime" slot-scope="lastTime">   
                    <div>{{lastTime ? lastTime : '-'}}</div>
                </div>
                <div slot="latestTime" slot-scope="latestTime">   
                    <div>{{latestTime ? latestTime : '-'}}</div>
                </div>
                <div slot="status" slot-scope="status">
                    <a-switch checked-children="上架" un-checked-children="下架" disabled :checked="status == 1 ? true : false" />
                </div>
                <template slot="operation" slot-scope="text, record">
                    <div class="editable-row-operations">
                        <a-button type="link" @click="update(record)">修改</a-button>
                        <a-popconfirm
                            title="是否确认删除当前数据?"
                            ok-text="Yes"
                            cancel-text="No"
                            @confirm="del(record)"
                        >
                            <a-button class="errorColor" type="link">删除</a-button>
                        </a-popconfirm>
                    </div>
                </template>
            </a-table>
        </a-page-header>

        <!-- 导出数据 -->
        <a-modal
            title="导出数据，每页10000条"
            :visible="downloadVisible"
            @ok="downladHandleOk"
            :confirm-loading="confirmLoading"
            @cancel="downloadVisible = false"
            >
            <div>
                <a-pagination v-model="current" :page-size.sync="pageSize" :total="total" show-less-items />
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { queryGoodsPurchaseForm , queryGoodsGeneral , queryGoodsCommonConfig , downloadGoodsPurchaseForm } from '@/api/newMall';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            storehouse: JSON.parse(localStorage.getItem('storehouseName')),
            storehouseId: JSON.parse(localStorage.getItem('storehouseId')),
            areaId: '0', // 固定商品区
            colorId: undefined,
            colorsList: [],
            grade: undefined,
            gradeList: [],
            services: this.$store.getters.roles.indexOf('updateGoodsPurchaseFormByCustomer') != -1 ? '1' : '0',
            goodsCateId: undefined,
            goodsList: [],
            goodsId: undefined,
            cateId: undefined,
            specId: undefined,
            specList: [],
            startTime: '', // 开始时间
            endTime: '', // 结束时间
            page: 1,
            size: 10,
            total: 0,
            dataList: [],
            isload: false,
            columns,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            statisticalDate: this.$route.query.statisticalDate,
            downloadVisible: false,
            confirmLoading: false,
            pageSize: 10000,
            current: 1,
        };
    },
    async created(){
        try {
            await this.getGoods();
            await this.getDescription('3');
            await this.getDescription('4');
            await this.getDescription('2');
            this.getData();
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        // 获取商品选择列表
        getGoods(){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId': _this.brandId,
                    'status': '1',
                    'page': 0,
                    'size': 99,
                }
                queryGoodsGeneral(params)
                .then(res => {
                    if(res.success){
                        _this.goodsList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 选择商品
        selGoods(item){
            console.log(item,'item')
            if(item){
                this.goodsId = item.split(',')[0];
                this.cateId = item.split(',')[1];
            }else{
                this.goodsId = undefined;
                this.cateId = undefined;
            }
            this.getData();
        },
        getData(){
            let _this = this;
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.areaId,
                'goodsId': _this.goodsId,
                'cateId': _this.cateId,
                'grade': _this.grade,
                'colorId': _this.colorId,
                'specId': _this.specId,
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'statisticalDate': _this.statisticalDate,
                'type': '1',
                'page': _this.page - 1,
                'size': _this.size,
            }
            _this.isload = true;
            queryGoodsPurchaseForm(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data.content;
                    _this.total = res.data.totalElements
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 获取商品说明和备注
        getDescription(type){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'type': type,
                    'page': 0,
                    'size': 99,
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        if(type == '2'){
                            _this.colorsList = res.data.content;
                        }else if(type == '3'){
                            _this.gradeList = res.data.content;
                        }else if(type == '4'){
                            _this.specList = res.data.content;
                        }else if(type == '5'){
                            _this.descriptionList = res.data.content;
                        }else{
                            _this.remarkList = res.data.content;
                        }
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        onChange(date, dateString) {
            console.log(date, dateString);
            if(date.length != 0){
                this.startTime = dateString[0];
                this.endTime = dateString[1];
            }else{
                this.startTime = '';
                this.endTime = '';
            }
            this.getData()
        },
        // 导出数据
        downloadData(){
            this.downloadVisible = true
        },
        downladHandleOk(){
            let _this = this
            _this.isload = true
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.areaId,
                'goodsId': _this.goodsId,
                'cateId': _this.cateId,
                'grade': _this.grade,
                'colorId': _this.colorId,
                'specId': _this.specId,
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'statisticalDate': _this.statisticalDate,
                'type': '1',
                'isExportExcel': '1',
                'size':_this.pageSize,
                'page':_this.current - 1,
            }
            downloadGoodsPurchaseForm(params)
            .then(res=>{
                _this.isload = false
                if(res){
                    _this.downloadVisible = false;
                    const content = res
                    console.log(res,"res")
                    let blob = new Blob([content], {type: 'application/x-excel'});
                    const fileName = `${_this.statisticalDate}上单表数据.xlsx`
                    if ('download' in document.createElement('a')) { // 非IE下载
                        const elink = document.createElement('a')
                        elink.download = fileName
                        elink.style.display = 'none'
                        elink.href = URL.createObjectURL(blob)
                        document.body.appendChild(elink)
                        elink.click()
                        URL.revokeObjectURL(elink.href) // 释放URL 对象
                        document.body.removeChild(elink)
                    } else { // IE10+下载
                        navigator.msSaveBlob(blob, fileName)
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
    }
}

</script>
<style scoped>

</style>